﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.IO;
using System.ComponentModel;

namespace SkypengerApp
{
    /// <summary>
    /// Logique d'interaction pour Conversation.xaml
    /// </summary>
    public partial class Conversation : Window
    {
        public string UserName { get; private set; }
        public string IP { get; private set; }
        public string ClientName { get; private set; }
        public TcpClient Socket { get; private set; }
        private StreamWriter _streamWriter;
        BackgroundWorker _worker;

        /// <summary>
        /// Initializes a new instance of the <see cref="Conversation"/> class.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="clientName">Name of the client.</param>
        /// <param name="ip">The ip.</param>
        /// <param name="socket">The socket.</param>
        public Conversation(string userName, string clientName, string ip, TcpClient socket)
        {
            InitializeComponent();

            UserName = userName;
            ClientName = clientName;
            IP = ip;
            Socket = socket;
            _streamWriter = new StreamWriter(Socket.GetStream());

            this.Loaded += new RoutedEventHandler(Conversation_Loaded);
            this.Closing += new CancelEventHandler(Conversation_Closing);
        }

        void Conversation_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                if (_worker.WorkerSupportsCancellation)
                    _worker.CancelAsync();
                _streamWriter.Close();
                Socket.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void Conversation_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _worker = new BackgroundWorker();
                _worker.DoWork += new DoWorkEventHandler(worker_DoWork);
                _worker.WorkerSupportsCancellation = true;
                _worker.RunWorkerAsync();
            }
            catch (Exception)
            {
            }
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (Socket != null)
            {
                NetworkStream stream = Socket.GetStream();
                while (stream != null)
                {
                    try
                    {
                        byte[] myReadBuffer = new byte[1024];
                        StringBuilder myCompleteMessage = new StringBuilder();
                        int numberOfBytesRead = 0;

                        // Incoming message may be larger than the buffer size.
                        while (stream.DataAvailable)
                        {
                            numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);

                            myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
                            Dispatcher.Invoke(new Action(delegate { this.TBk_Conversation.Text += myCompleteMessage; }));
                        }
                    }
                    catch (Exception ex)
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
        }

        private void Btn_Envoyer_Click(object sender, RoutedEventArgs e)
        {
            if (!Socket.Connected || !Socket.Client.Poll(-1, SelectMode.SelectWrite))
            {
                this.TBk_Conversation.Text += "Votre contact est déconnecté\n";
                return;
            }

            if (_streamWriter != null)
            {
                string msg = UserName + ": " + TB_Message.Text;
                this.TBk_Conversation.Text += msg + "\n";
                TB_Message.Text = "";

                try
                {
                    _streamWriter.WriteLine(msg);
                    _streamWriter.Flush();
                }
                catch (Exception)
                {
                }
            }
        }
    }
}
